package com.gem.netty.hanlder;

import com.alibaba.fastjson.JSONObject;
import com.gem.entity.Game;
import com.gem.enums.GemType;
import com.gem.factory.game.GameFactory;
import com.gem.netty.delay.Heart;
import com.gem.netty.entity.ClientContent;
import com.gem.netty.entity.CurrentUser;
import com.gem.netty.message.MessageFactory;
import com.gem.netty.session.SessionFactory;
import com.gem.utils.IPUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: Xhy
 * CreateTime: 2022-09-20 13:45
 */

@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {


        TextWebSocketFrame frame=(TextWebSocketFrame)msg;
        ClientContent content = JSONObject.parseObject(frame.text(), ClientContent.class);
        content.setCtx(ctx);
        // 处理消息
        MessageFactory.get(content.getType()).handler(content);

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }

    /**
     * 用户关闭连接后把当前用户放入延迟队列200秒。期间用户如果重新上线会激活连接建立,则把延迟队列当中删掉
     * 如果延迟队列时间到则把用户和通道关闭
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        Heart.getInstance().add(IPUtils.getIp(channel),200);
    }

}
